package com.emm.yixun.website.service.pmo;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import com.emm.yixun.common.model.*;
import com.emm.yixun.common.model.enums.PmoPushEnum;
import com.emm.yixun.system.service.pmo.PmoDynamicDataServiceFacade;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.emm.yixun.common.enums.ResponseEnums;
import com.emm.yixun.common.model.dto.PmoLogDto;
import com.emm.yixun.common.model.dto.ProjectPmoDto;
import com.emm.yixun.common.model.enums.MerchantEnum;
import com.emm.yixun.common.model.pmo.GraphicalVo;
import com.emm.yixun.common.model.pmo.LevelDynamiSalesData;
import com.emm.yixun.common.model.pmo.SalesBackOfYear;
import com.emm.yixun.common.response.Response;
import com.emm.yixun.common.response.ResponseList;
import com.emm.yixun.common.utils.DateStyle;
import com.emm.yixun.common.utils.DateUtils;
import com.emm.yixun.common.utils.MD5;
import com.emm.yixun.common.utils.RequestUtil;
import com.emm.yixun.estate.service.ProjectPmoServiceFacade;
import com.emm.yixun.estate.service.ProjectServiceFacade;
import com.emm.yixun.system.service.MerchantServiceFacade;
import com.emm.yixun.system.service.PmoLogServiceFacade;
import com.emm.yixun.website.common.utils.security.ShiroUtil;
import com.emm.yixun.website.constant.PmoConfig;


@Service("levelProjectDataService")
public class LevelProjectDataServiceImpl implements LevelProjectDataService {
	
	private final Logger logger = LoggerFactory.getLogger(LevelProjectDataServiceImpl.class); 

	@Autowired
	private ProjectServiceFacade projectServiceFacade;
	
	@Autowired
	private PmoConfig pmoConfig;
	
	@Autowired
	private PmoLogServiceFacade pmoLogServiceFacade;
	
	@Autowired
	private ProjectPmoServiceFacade projectPmoServiceFacade;
	
	@Autowired
	private MerchantServiceFacade merchantServiceFacade;
	@Autowired
	private PmoDynamicDataServiceFacade pmoDynamicDataServiceFacade;

	@Override
	public void sendLevelProjectData(String pmoProjectCode, String month,boolean isAll) {
		User user = ShiroUtil.getCurrentUser();
		try {
			if(user.getMerchantId().compareTo(new Long(MerchantEnum.GREEN_TOWN.getNo()))==0){
				if(isAll){  
					//从201701 - 至今  每个月份的动态数据推送
					String minDate = DateUtils.DateToString(DateUtils.getCurrYearFirst(), DateStyle.YYYYMM.getValue());
					String maxDate = DateUtils.DateToString(new Date(), DateStyle.YYYYMM.getValue());
					List<String> dateList = DateUtils.getMonthBetween(minDate, maxDate);
					for (int i = 0; i < dateList.size(); i++) {
						sendData(pmoProjectCode, dateList.get(i),null);
					}
				}else{
					sendData(pmoProjectCode, month,null);
				}
				
			}
		} catch (Exception e) {
			logger.error("send ProjectData error:",e);
		}
	}

	
	public void sendData(String pmoProjectCode, String month,List<SalesBackOfYear> salesBackOfYear) throws Exception{
		User user = ShiroUtil.getCurrentUser();
		if(sendValid((user.getMerchantId()))){
			Response<LevelDynamiSalesData> response = pmoDynamicDataServiceFacade.quereyLevelDynamiSalesData(pmoProjectCode,month);
			//Response<LevelDynamiSalesData> response = projectServiceFacade.quereyLevelDynamiSalesData(pmoProjectCode,month);

			boolean pmoPushFlag = projectServiceFacade.checkPmoPush(pmoProjectCode);

			if(pmoPushFlag){
				response.getEntity().setSalesBackOfYears(salesBackOfYear);
				LevelDynamiSalesData levelDynamiSalesData = response.getEntity();
				String json = JSON.toJSONString(levelDynamiSalesData);
				System.err.println(json);
				String clientKey = pmoConfig.getClientKey();
				String seq = pmoConfig.getSeq();
				String digest = MD5.md5(clientKey + seq + pmoConfig.getClientPwd()).toUpperCase();
				String url = pmoConfig.getRequest_url() + "/api/v1/pmo/project-dynamic-sale/" + pmoProjectCode;
				com.emm.yixun.common.utils.ResponseBody responseBody = RequestUtil.buildRequest(json, url, clientKey, seq,digest);
				PmoLogDto pmoLogDto = new PmoLogDto();
				pmoLogDto.setMerchantId(user.getMerchantId());
				pmoLogDto.setDirection("1");
				if (responseBody.getCode().equals(ResponseEnums.RESPONSEENUMS_000000.getCode())) {// 成功
					pmoLogDto.setStatus("1");
				} else {
					pmoLogDto.setStatus("2");
				}
				pmoLogDto.setRequestParams(json);
				pmoLogDto.setDelFlag("0");
				pmoLogDto.setInterfaceName("销售动态信息");
				pmoLogDto.setReturnResult(JSON.toJSONString(responseBody));
				pmoLogServiceFacade.save(pmoLogDto);
			}
		}
	}

	@Override
	public boolean sendValid(Long id) {
		Response<Merchant> merchantResponse = merchantServiceFacade.findById(id);
		if(merchantResponse.isSuccess()&&merchantResponse.getEntity()!=null){
			String information = merchantResponse.getEntity().getPhoneInformation();
			com.alibaba.fastjson.JSONArray jsonArray = JSON.parseArray(information);
			for (int i = 0; i < jsonArray.size(); i++) {
				com.alibaba.fastjson.JSONObject jsonObject = jsonArray.getJSONObject(i);
				String type = jsonObject.getString("type");
				String status = jsonObject.getString("status");
				if("5".equals(type)&&"1".equals(status)){
					return true;
				}
			}
		}
		return false;
	}

	@Override
	public String getProjectPmoCode(Long projectId) {
		ProjectPmoDto pmoDto = new ProjectPmoDto();
		pmoDto.setProjectId(projectId);
		ResponseList<ProjectPmo> responseList =  projectPmoServiceFacade.findByDto(pmoDto);
		if(responseList.isSuccess()&&responseList.getEntity()!=null){
			return responseList.getEntity().get(0).getPmoProjectCode();
		}
		return null;
	}


	@Override
	public HashMap<String,List<GraphicalVo<Double>>> findDynamiSalesData(Long projectId, String year) {
		HashMap<String,List<GraphicalVo<Double>>> map = new HashMap<String, List<GraphicalVo<Double>>>();
		List<GraphicalVo<Double>> graphicalList = new ArrayList<GraphicalVo<Double>>(); //动态货值，目标货值汇总
		GraphicalVo<Double> dynamiValue =new GraphicalVo<Double>();
		dynamiValue.setName("动态货值");
		List<Double> dynamiData = new ArrayList<Double>();
		try {
			String minDate = DateUtils.DateToString(DateUtils.StringToDate(year+"01"), DateStyle.YYYYMM.getValue());
			String maxDate = DateUtils.DateToString(DateUtils.StringToDate(year+"12"), DateStyle.YYYYMM.getValue());
			List<String> dateList = DateUtils.getMonthBetween(minDate, maxDate);
			String pmoProjectCode = getProjectPmoCode(projectId);
			for (int i = 0; i < dateList.size(); i++) {

				Response<LevelDynamiSalesData> response = pmoDynamicDataServiceFacade.quereyLevelDynamiSalesData(pmoProjectCode,dateList.get(i));
				//Response<LevelDynamiSalesData> response = projectServiceFacade.quereyLevelDynamiSalesData(pmoProjectCode,dateList.get(i));
				LevelDynamiSalesData levelDynamiSalesData = response.getEntity();
				dynamiData.add(levelDynamiSalesData.getData().getDynamiValue());
			}
			dynamiValue.setData(dynamiData);
			graphicalList.add(dynamiValue);
			map.put("dynamiValueList", graphicalList);
		} catch (Exception e) {
			logger.error("error",e);
		}
		return map;
	}
	



	@Override
	public List<GraphicalVo<Double>> findSaleData(List<SaleReturnPmo> salePmo,boolean isSale,String[] title) {
		List<GraphicalVo<Double>> saleData = new ArrayList<GraphicalVo<Double>>();
		List<Double> saleValue = new ArrayList<Double>();
		GraphicalVo<Double> vo = new GraphicalVo<Double>();
		vo.setName(title[0]);
		GraphicalVo<Double> returnVo = new GraphicalVo<Double>();
		returnVo.setName(title[1]);
		List<Double> returnValue = new ArrayList<Double>();
		try {
			for (SaleReturnPmo sale:salePmo) {
				if(isSale){
					saleValue.add(sale.getSalePlan()==null?0D:new Double(sale.getSalePlan()));
					returnValue.add(sale.getSaleActual()==null?0D:new Double(sale.getSaleActual()));
				}
			}
			vo.setData(saleValue);
			returnVo.setData(returnValue);
			saleData.add(vo);
			saleData.add(returnVo);
		} catch (Exception e) {
			logger.error("report error",e);
		}
		return saleData;
	}


	@Override
	public void sendLevelDyData(String projectPmoCode, String month, List<SalesBackOfYear> salesBackOfYear) throws Exception {
		sendData(projectPmoCode, month, salesBackOfYear);
	}

}
